<?php

namespace App\Http\Controllers;

use App\Services\Database;
use App\Models\Database as DBModel;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;


class DatabaseController extends Controller
{
    /**
     * 数据库列表
     * @param Request $i
     * @return JsonResponse
     */
    public function index(Request $i) : JsonResponse {
        $userId = $i->input('userId', 1);
        $databases = Database::search($userId);
        return $this->success($databases);
    }

    /**
     * 数据库详情
     * @param Request $i
     * @return JsonResponse
     */
    public function detail(Request $i) : JsonResponse{
        $id = $i->input('id');
        $dbInfo = DBModel::find($id);
        return $this->success($dbInfo);
    }

    /**
     * 创建数据库
     * @param Request $i
     * @return JsonResponse
     */
    public function create(Request $i) : JsonResponse {

        $dbInfo = $i->only(['local', 'name', 'driver', 'db_host', 'db_port', 'db_name', 'db_user', 'db_password', 'db_charset', 'db_collation', 'table_prefix']);
        $dbInfo['user_id']  = $i->input('tokenUser');
        if ($dbInfo['local']) {
            $defaultDB = config('database.connections.mysql');
            $dbInfo['driver']   = $defaultDB['driver'];
            $dbInfo['db_host']  = $defaultDB['host'];
            $dbInfo['db_port']  = $defaultDB['port'];
            $dbInfo['db_user']  = $defaultDB['username'];
            $dbInfo['db_password']  = $defaultDB['password'];
            $dbInfo['db_charset']   = $defaultDB['charset'];
            $dbInfo['db_collation'] = $defaultDB['collation'];
        }

        $res = Database::create($dbInfo);
        if ($res == false) {
            return $this->fail(Database::error());
        }
        return $this->success($res);
    }

    public function update(Request $i) {
        $id     = $i->input('id');
        $dbInfo = $i->input('dbInfo');
        Database::update($id, $dbInfo);
        return $this->json();
    }

    /**
     * @param Request $i
     * @return JsonResponse
     */
    public function delete(Request $i) : JsonResponse {
        $id     = $i->input('id');
        $userId = $i->input('tokenUser');
        Database::delete($userId, $id);
        return $this->json();
    }

    public function setDefault(Request $i) {
        $id     = $i->input('id');
        $userId = $i->input('tokenUser');
        Database::set_default($userId, $id);
        return $this->json();
    }
}
